#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
 * 对变量进行typedef
 * */
#define NAMEMAX 1024
typedef struct student_st
{
	int id;
	char *name;
	int math;
	int chinese;
}STU;

void stu_set(STU *p,STU *q)
{
	p ->id = q->id;
	p->name=malloc(strlen(q->name)+1);
	if (p->name ==NULL)
		exit(1);
	strcpy(p->name,q->name);
	p->math = q ->math;
	p->chinese = q ->chinese;
//	free(p->name);此处free 会造成stu_show() 无法获取p->name

}

void stu_show(STU *p)
{
	printf("%d %s %d %d\n",p->id,p->name,p->math,p->chinese);
}


void stu_changname(STU *p,char newname[NAMEMAX])
{
	free(p->name);

	p->name = malloc(strlen(newname)+ 1);//为什么不free？ 要怎样free??
	strncpy(p->name, newname,NAMEMAX);
//	free(p->name);  此处free会造成 错误
}

void menu(void)
{
	printf("\n\n1.set\n2.changename\n3.show\n4.out\n\n");
}

int main(void)
{
	STU stu,tmp;
	char newname[NAMEMAX];	

	char flag = 1,key = 0;
	int ret = 0;
	while(flag)
	{
		menu();

		printf("plz enter for the key(q or Q for quit)");
		ret = scanf("%d",&key);
		if(ret != 1)
		{
			break;
		}
		if (key == 4)
		{	
			flag = 0;
		}
		else if (key == 1)
		{
			tmp.name = malloc(NAMEMAX);
			printf("plz enter for the stu[id name math chinese]:\n");
			scanf("%d%s%d%d",&tmp.id,tmp.name,&tmp.math,&tmp.chinese);
			stu_set(&stu,&tmp);
		}
		else if(key == 2)
		{		
			printf("plz enter the newname:\n");
			scanf("%s",newname);
			stu_changname(&stu,newname);
		}
		else if(key == 3)
		{
			stu_show(&stu);		
		}
		else
		{
			exit(1);
		}
		
		sleep(1);	
	}
	printf("ths for you use this system!\n");
	exit(0);
}
